// pages/physical-confirm/physical-confirm.js
Page({
	data: {
		patientName: '',
		patientCard: '610*********0989',
		packageName: '',
		unitPrice: '0.00',
		totalPrice: '0.00',
		cardBalance: '0.00'
	},

	onLoad(options) {
		console.log('体检确认支付页面加载')
		console.log('页面参数:', options)
		
		if (options.patient) {
			this.setData({
				patientName: options.patient
			})
		}
		
		if (options.package) {
			try {
				const packageData = JSON.parse(options.package)
				this.setData({
					packageName: packageData.name,
					unitPrice: packageData.price,
					totalPrice: packageData.price
				})
			} catch (e) {
				console.error('解析套餐数据失败:', e)
			}
		}
		
		if (options.totalPrice) {
			this.setData({
				totalPrice: options.totalPrice
			})
		}
		
		// 获取卡内余额
		this.loadCardBalance()
	},

	// 加载卡内余额
	loadCardBalance() {
		const balance = wx.getStorageSync('currentBalance') || '4100.00'
		this.setData({
			cardBalance: balance
		})
	},

	// 去充值
	goRecharge() {
		console.log('跳转到充值页面')
		wx.navigateTo({
			url: '/pages/2411Ayiliao-pages/recharge/outpatient'
		})
	},

	// 查看体检须知
	viewNotice() {
		console.log('查看体检须知')
		wx.showModal({
			title: '体检须知',
			content: '1. 体检前请保持空腹8-12小时\n2. 请携带有效身份证件\n3. 体检当天请穿着宽松衣物\n4. 如有特殊情况请提前告知医生',
			showCancel: false,
			confirmText: '我知道了'
		})
	},

	// 确认支付
	confirmPayment() {
		console.log('确认支付')
		
		const currentBalance = parseFloat(this.data.cardBalance)
		const paymentAmount = parseFloat(this.data.totalPrice)
		
		if (currentBalance < paymentAmount) {
			wx.showModal({
				title: '余额不足',
				content: '卡内余额不足，请先充值',
				showCancel: false,
				confirmText: '去充值',
				success: (res) => {
					if (res.confirm) {
						this.goRecharge()
					}
				}
			})
			return
		}
		
		// 扣除余额
		const newBalance = (currentBalance - paymentAmount).toFixed(2)
		wx.setStorageSync('currentBalance', newBalance)
		
		// 记录交易历史
		const transactionHistory = wx.getStorageSync('transactionHistory') || []
		transactionHistory.push({
			type: 'expense',
			amount: paymentAmount.toFixed(2),
			description: '体检费用',
			package: this.data.packageName,
			patient: this.data.patientName,
			time: new Date().toLocaleString()
		})
		wx.setStorageSync('transactionHistory', transactionHistory)
		
		// 跳转到预约成功页面
		wx.navigateTo({
			url: '/pages/physical-success/physical-success?patient=' + this.data.patientName + 
				 '&package=' + JSON.stringify({
					 name: this.data.packageName,
					 price: this.data.totalPrice
				 }) + 
				 '&date=2025-01-03'
		})
	},

	onShow() {
		// 每次显示页面时同步余额
		this.loadCardBalance()
	}
})
